using AutoMapper;
using BackData;
using Domain.DTOs.ProcessSteps;
using Domain.工艺工序;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Makesteps;
using System.Collections.Generic;

namespace Team.API.Applocation.Hanldler.Makesteps
{
    /// <summary>
    /// 成品工艺工序分页查询处理器
    /// </summary>
    public class GetMakestepListHandler : IRequestHandler<GetMakestepListCommand, APIPaging<MakestepListDTO>>
    {
        private readonly IMapper mapper;
        private readonly IRepository<Makestepmodel> repository;

        public GetMakestepListHandler(IMapper mapper, IRepository<Makestepmodel> repository)
        {
            this.mapper = mapper;
            this.repository = repository;
        }

        public async Task<APIPaging<MakestepListDTO>> Handle(GetMakestepListCommand request, CancellationToken cancellationToken)
        {
            // 仅查询顶级（成品级）工序，过滤已删除数据
            var query = repository.GetAll().Where(x => !x.IsDel && x.Parentid == 0);

            if (!string.IsNullOrWhiteSpace(request.Goodsname))
            {
                query = query.Where(x => x.Goodsname == request.Goodsname);
            }
            if (!string.IsNullOrWhiteSpace(request.Version))
            {
                query = query.Where(x => x.Version == request.Version);
            }
            if (request.IsUse.HasValue)
            {
                query = query.Where(x => x.IsUse == request.IsUse.Value);
            }

            // 分页查询
            var total = await query.CountAsync();
            var entities = await query.OrderBy(x => x.Processcode).ToPageListAsync(request.Pageindex, request.Pagesize);
            var list = mapper.Map<List<MakestepListDTO>>(entities);

            return new APIPaging<MakestepListDTO>
            {
                Code = StateCode.OK,
                Message = "查询成功",
                Totalcount = total,
                ListResult = list
            };
        }
    }
}

